package com.xiashitech.agent.rule.usermatch.inst;

import cn.hutool.core.util.StrUtil;
import com.google.auto.service.AutoService;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.constants.SpecialConfigString;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.biz.userinfo.springsecurity.AuthenticationData;
import com.xiashitech.agent.rule.usermatch.base.UserInfoMatchRule;
import com.xiashitech.agent.utils.JsonUtil;
import com.xiashitech.agent.utils.XSUtil;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;
import ognl.Ognl;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

//@AutoService(UserInfoMatchRule.class)
public class XSAuthenticationV2UserMatch<REQUEST> implements UserInfoMatchRule<REQUEST>{
    @Override
    public UserRequest extractUserInfo(REQUEST request) {
        UserRequest userRequest = null;
        try {
            if (request == null || !(request instanceof AuthenticationData)) {
                return UserRequest.builder().build();
            }
            userRequest = UserRequest.builder().requestDate(String.valueOf(new Date().getTime())).build();
            AuthenticationData authenticationData = (AuthenticationData) request;
            Object principal = authenticationData.getPrincipal();
            if (principal instanceof String){
                if (JsonUtil.isJson((String)principal)){
                    //根据项目实际情况 适配JSON
                }else {
                    //根据项目实际情况 适配原生字符串
                }
            }else {
                // 标准的 JavaBean 或 Map
                String userIdPath = XSUtil.getAgentConfigBySystemId(AgentConfigDTO.getConfig().getUseridpath());
                String realIdPath = StrUtil.subAfter(userIdPath, SpecialConfigString.BIZ_USER_SS.getConfiString(), true);

                if (XSUtil.isNotEmpty(realIdPath)){
                    userRequest.setUserid(String.valueOf(Ognl.getValue(realIdPath, principal)));
                }
            }
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }

        return userRequest;
    }


    @Override
    public Integer getOrder() {
        return 7;
    }
}
